#include <SPI.h>
#include <Ethernet.h>
#include <EEPROM.h>
#include <WString.h>


byte mac[6] = { 0xBE, 0xEF, 0x00, 0x00, 0x00, 0x00 };
char macstr[18];

EthernetServer server(80);

void setup() {
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  delay(1000);
  if (EEPROM.read(1) == '#')
  {

    for (int i = 2; i < 6; i++)
    {
      mac[i] = EEPROM.read(i);
    }
  }
  else
  {
  Serial.println("No MAC Configured");
  randomSeed(analogRead(2));
    for (int i = 2; i < 6; i++)
    {
      mac[i] = random(0, 255);
      EEPROM.write(i, mac[i]);
    }
  EEPROM.write(1, '#');
  }
  snprintf(macstr, 18, "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1],
mac[2], mac[3], mac[4], mac[5]);

  // Start up networking
  Serial.print("DHCP (");
  Serial.print(macstr);
  Serial.println(")");
  Ethernet.begin(mac);
  Serial.print("success: ");
  Serial.println(Ethernet.localIP());

  server.begin();
  Serial.println("Server Ready!");

}
  int outputValues[] = {1,0,0,0,1,1,0,1,0,1,1,1,1,1,0,1,0,0,0,1};

String readString = String(100);


void loop() {
  readString = "";
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        if (readString.length() < 100) {
          readString += c;
        }
       // Serial.write(c);

        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          Serial.println(readString);

          client.print("{\"outputs\": [");
          for (int i = 0; i < (sizeof(outputValues)/sizeof(int)); i++)
          {
            client.print("{\"output");
            client.print(i);
            client.print("\": \"");
            client.print(outputValues[i]);
            client.print("\"}");
            if (i < (sizeof(outputValues)/sizeof(int) -1) )
            {
              client.print(", ");
            }
          }
          client.print("]}");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disonnected");
    readString="";
  }
}
